package com.hula.onion.book.server.spider.platforms.xiaoyoucai;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("xiaoYouCaiSpider")
public class XiaoYouCaiSpider extends SpiderCommon {

    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.xiaoyoucai.com/dt/login.action";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.xiaoyoucai.com/accountInfo";

    @Autowired
    private XiaoYouCaiSpiderHelper spiderHelper;

    /**
     * 执行爬取操作
     */
    @Override
    public CommonResponse execute() {
        //2. 模拟登陆
        String responseStr = HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if(StringUtils.isEmpty(responseStr)){
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        logger.info("[xiaoYouCaiSpider] Http response result:{}", responseStr);
        System.out.println(responseStr);
        String suc = responseStr.split("#")[0];

        //登陆成功
        if ("1".equals(suc)) {
            //2.1 爬取用户详细信息
            String result = HttpUtils.get(GET_ACCOUNT_INFO_URL, getHttpContext());
            logger.info("[xiaoYouCaiSpider] Http response account result:{}", result);
            //2.2 解析JSON
            return spiderHelper.parseAccountBalance(result);
        } else {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
    }


    @Override
    public String getLoginPageURL() {
        return LOGIN_URL;
    }

}

